//
//  Client_JiHuoController.swift
//  Wmsmobile
//
//  Created by wangshuning on 16/9/26.
//  Copyright © 2016年 www.hd123.com. All rights reserved.
//

import UIKit

class Client_JiHuoController: HDFounctionBaseController , HDBarcodeInputCellInputDelegate , HDFounctionBottomViewDelegate,HDJiHuoNumberTableViewCellDelegate{
    //    //MARK: - property
    var firstAppear: Bool = true
    var piJobId: String?
    var piStoreCode: String?
    var poChestInfo: String?
    var str: String?
    var piAttachMentInfo: String?
    var s1: [String : String]?
    var s2: [String : String]?
    var s3: [String : String]?
    var s4: [String : String]?
    var piSrt: String?
    var endFlag : Bool = false
    var emptyFlag = true
    
    var dataArray0:[[String : String]] = [["title" : "配货作业号"] , ["title" :"门店代码"], ["title" : "门店名称"]]
    var dataArray1:[[String : String]]?{
        didSet{
            self.tableView.reloadData()
//            print("dataArray1 = \(dataArray1)")
        }
    }
    var dataArray2:[[String : String]]?{
        didSet{
            self.tableView.reloadData()
//            print("dataArray2= \(dataArray2)")
        }
    }
    
    lazy private var bottomView:HDFounctionBottomView = {
        let view = HDFounctionBottomView(array: ["提交", "清屏"])
        return view
    }()
    
    //MARK: - lifeCycle
    override func viewDidLoad() {
        self.tableView.registerClass(HDBarcodeInputCell.self, forCellReuseIdentifier: "HDBarcodeInputCell")
        self.tableView.registerClass(HDBarcodeInputCell.self, forCellReuseIdentifier: "HDBarcodeInputCell")
        self.tableView.registerClass(HDProductInfocell.self, forCellReuseIdentifier: "HDProductInfocell")
        self.tableView.registerClass(HDBinSpecTableviewCell.self, forCellReuseIdentifier: "HDBinSpecTableviewCell")
        self.tableView.registerClass(HDJiHuoTableViewCell.self, forCellReuseIdentifier: "HDJiHuoTableViewCell")
        self.tableView.registerClass(HDJiHuoNumberTableViewCell.self, forCellReuseIdentifier: "HDJiHuoNumberTableViewCell")
        self.tableView.addSubview(self.bottomView)
        self.tableView.contentInset.bottom = bottomView.height
        self.bottomView.delegate = self
        
        super.viewDidLoad()
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if self.firstAppear == true{
            let indexPath = NSIndexPath(forRow: 0, inSection: 0)
            let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! HDBarcodeInputCell
            UIView.animateWithDuration(Double(indexPath.row) * 0.1, animations: {
                self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: false)
                }, completion: { (true) in
                    cell.state = inputViewState.activated
            })
            self.firstAppear = false
        }
    }
    //MARK: - delegate
    func finishjiHuoNumInput(cell: HDJiHuoNumberTableViewCell) {
        
        let indexPath = self.tableView.indexPathForCell(cell)
        let celltext = cell.label3.text
            if indexPath?.section == 1 {
                self.dataArray1![(indexPath?.row)!].updateValue(celltext ?? "", forKey: "right")
            }else{
                self.dataArray2![(indexPath?.row)!].updateValue(celltext ?? "", forKey: "right")
            }
    }
    
    func returnjiHuoNumInput(cell: HDJiHuoNumberTableViewCell){
        
        let indexpath = self.tableView.indexPathForCell(cell)
        switch indexpath!.section {
        case 1:
            //是否是本组最后一个cell
            if indexpath!.row == dataArray1!.count - 1 {
                self.goNextCell(cell, nextInsexPath: NSIndexPath(forItem: 0, inSection: 2))
            }else{
                self.goNextCell(cell, nextInsexPath: NSIndexPath(forItem: indexpath!.row + 1, inSection: indexpath!.section))
            }
            break
        case 2:
            //是否是本组最后一个cell
            if indexpath!.row == dataArray2!.count - 1 {
//                cell.label3.enabled = true
                cell.label3.resignFirstResponder()
                
            }else{
                self.goNextCell(cell, nextInsexPath: NSIndexPath(forItem: indexpath!.row + 1, inSection: indexpath!.section))
            }
            break
        default:
            break
        }

        
    }
    
    func clickFounctionBottom(position: NSInteger) {
        
        if position == 1{
        }
        
        switch position {
        case 0:
            self.tableView.scrollToRowAtIndexPath(NSIndexPath(forItem: 0,inSection: 0) , atScrollPosition: UITableViewScrollPosition.Top, animated: false)
            let piOrdNumCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) as! HDBarcodeInputCell
            let celltext = piOrdNumCell.codeInputView.textField.text
            let piOrdNumCell1 = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 0)) as! HDBarcodeInputCell
            let celltext1 = piOrdNumCell1.codeInputView.textField.text
            if celltext?.characters.count < 1{
                self.showMessage("请输入配货作业", success: false)
                return
            } else if celltext1?.characters.count < 1{
                self.showMessage("请输入配货作业", success: false)
                return
            }
            
            if self.poChestInfo == "$$" {
//                self.showMessage("请设置容器内容", success: false)
                self.getData(["piJobId":self.piJobId!, "piStoreCode ":self.piStoreCode!,"piOperator" : (userInfo?.userName)!, "piChestInfo" : " ","piAttachMentInfo":self.piAttachMentInfo!], bodyMethod: "updCltChk", suffix: "330", success: { (dict) in
                    self.showMessage("提交成功", success: true)
                    self.tableView.reloadData()
                    //                self.reuseFlag = false
                    self.goNextCell(self.activedCell ?? piOrdNumCell, nextInsexPath: NSIndexPath(forItem: 0, inSection: 0))
                    let firstCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as! HDBarcodeInputCell
                    firstCell.codeInputView.textField.text = ""
                    let secondCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 1, inSection: 0)) as! HDBarcodeInputCell
                    secondCell.codeInputView.textField.text = ""
                    }, failed: { dict in
                })
            }
            if self.piAttachMentInfo == "$$" {
//                self.showMessage("请设置附件内容", success: false)
                self.getData(["piJobId":self.piJobId!, "piStoreCode ":self.piStoreCode!,"piOperator" : (userInfo?.userName)!, "piChestInfo" : self.poChestInfo!,"piAttachMentInfo":" "], bodyMethod: "updCltChk", suffix: "330", success: { (dict) in
                    self.showMessage("提交成功", success: true)
                    self.tableView.reloadData()
                    //                self.reuseFlag = false
                    self.goNextCell(self.activedCell ?? piOrdNumCell, nextInsexPath: NSIndexPath(forItem: 0, inSection: 0))
                    let firstCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as! HDBarcodeInputCell
                    firstCell.codeInputView.textField.text = ""
                    let secondCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 1, inSection: 0)) as! HDBarcodeInputCell
                    secondCell.codeInputView.textField.text = ""
                    }, failed: { dict in
                })
            }
            if self.poChestInfo != "$$" && self.piAttachMentInfo != "$$"{
                self.getData(["piJobId":self.piJobId!, "piStoreCode ":self.piStoreCode!,"piOperator" : (userInfo?.userName)!, "piChestInfo" : self.poChestInfo!,"piAttachMentInfo":self.piAttachMentInfo!], bodyMethod: "updCltChk", suffix: "330", success: { (dict) in
                    self.showMessage("提交成功", success: true)
                    self.tableView.reloadData()
                    //                self.reuseFlag = false
                    self.goNextCell(self.activedCell ?? piOrdNumCell, nextInsexPath: NSIndexPath(forItem: 0, inSection: 0))
                    let firstCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as! HDBarcodeInputCell
                    firstCell.codeInputView.textField.text = ""
                    let secondCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 1, inSection: 0)) as! HDBarcodeInputCell
                    secondCell.codeInputView.textField.text = ""
                    }, failed: { dict in
                })
            }
            
            break
        case 1:
            let firstCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) as! HDBarcodeInputCell
            if firstCell.codeInputView.textField.text?.characters.count == 0 {
                return
            }
            
            let alertController = UIAlertController(title: "提示", message: "确定清除所有信息？", preferredStyle: UIAlertControllerStyle.Alert)
            alertController.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil))
            alertController.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) in
                self.resetController(self.activedCell!, nextItem: 0, nextSection: 0, message: nil, success: true)
            }))
            self.presentViewController(alertController, animated: true, completion: nil)
            
            return
        default:
            break
        }
        
    }
    func clicKReturn(cell: HDBarcodeInputCell) {
        
        let indexpath = self.tableView.indexPathForCell(cell)
        
        switch indexpath!.section * 100 + indexpath!.row {
        case 0:
            guard cell.codeInputView.textField.text?.characters.count > 0 else{
                self.showMessage("请输入配货作业号", success: false)
                return
            }
            let cellText = cell.codeInputView.textField.text!
            self.goNextCell(cell, nextInsexPath: NSIndexPath(forItem: 1, inSection: 0))
            self.piJobId = cellText
        case 1:
            guard cell.codeInputView.textField.text?.characters.count > 0 else{
                self.showMessage("请输入门店代码", success: false)
                return
            }
            let celltext = cell.codeInputView.textField.text!
            self.getData(["piJobId":self.piJobId!,"piStoreCode":celltext,"piOperator":(userInfo?.userName)!], bodyMethod: "startCltChk", suffix: "330", success: { (dict) in
                self.downloadData += dict
                print("self.downloadData=\(self.downloadData)")
                let cell2 = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 2, inSection: 0)) as! HDProductInfocell
                self.piStoreCode = celltext
                cell2.textField.text = dict["poStoreName"]
                let produtionCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 2, inSection: 0)) as! HDProductInfocell
                produtionCell.textField.text = self.downloadData["poStoreName"]!
                self.poChestInfo = self.downloadData["poChestInfo"] ?? ""
                let str = dict["poChestInfo"] ?? ""
                let stringFinal = str.stringByReplacingOccurrencesOfString("$$", withString: ":")
                let array = stringFinal.componentsSeparatedByString("^^")
                var tempArrayTop = [[String : String]]()
                for i in 0 ..< array.count{
                    var dict = [String : String]()
                    let value1 = array[i].componentsSeparatedByString(":").first
                    dict.updateValue(value1!, forKey: "left")
                    let value2 = array[i].componentsSeparatedByString(":").last
                    dict.updateValue(value2!, forKey: "right")
                    tempArrayTop.append(dict)
                }
                self.dataArray1 = tempArrayTop
                self.getData(["piJobId":self.piJobId!,"piStoreCode":celltext], bodyMethod: "GetAttachmentInfo", suffix: "330", success: { (dict) in
                    self.downloadData += dict
                    print("self.downloadData=\(self.downloadData)")
                    //                    self.piAttachMentInfo = self.downloadData["poAttachMentInfo"] ?? ""
                    let str = dict["poAttachMentInfo"] ?? ""
                    guard strlen(str ?? "") > 0 else {
                        cell.state = inputViewState.wrong
                        return
                    }
                    let stringFinal = str.stringByReplacingOccurrencesOfString("$$", withString: ":")
                    let array = stringFinal.componentsSeparatedByString("^^")
                    var tempArrayTop = [[String : String]]()
                    for i in 0 ..< array.count{
                        var dict = [String : String]()
                        let value1 = array[i].componentsSeparatedByString(":").first
                        dict.updateValue(value1!, forKey: "left")
                        let value2 = array[i].componentsSeparatedByString(":").last
                        dict.updateValue(value2!, forKey: "right")
                        tempArrayTop.append(dict)
                    }
                    
                    self.dataArray2 = tempArrayTop
                    if self.dataArray1 == nil{
                        return
                    }else{
                     self.goNextCell(cell, nextInsexPath: NSIndexPath(forItem:0, inSection: 1))
                    }
                    }, failed: { (dict) in
                        
                })
                }, failed: {_ in
                    cell.state = inputViewState.wrong
            })
            break
        default:
            break
        }
        
    }
    //MARK: - private
    func getStringBettwen(textLeft: String , textRight: String , inString: String) -> (String?){
        let string1 = inString.componentsSeparatedByString(textLeft).last
        
        guard string1 != nil else{
            return nil
        }
        let string2 = string1!.componentsSeparatedByString(textRight).first
        return string2
    }
    override func isEmpty() -> (Bool) {
        if dataArray1?.count > 0 {
            return false
        }else{
            return true
        }
    }
    //MARK: - tableviewDatasource
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 3
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 3
        case 1:
            return dataArray1?.count ?? 1
        case 2:
            return dataArray2?.count ?? 1
        default:
            return 0
        }
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellOriginal:HDFounctionBaseCell?
        switch (indexPath.section) * 1000 + (indexPath.row) {
        case 0:
            cellOriginal = tableView.dequeueReusableCellWithIdentifier("HDBarcodeInputCell") as! HDBarcodeInputCell
            let cell = cellOriginal as! HDBarcodeInputCell
            cell.titleView.text = "配货作业号"
            cell.InputDelegate = self
        case 1:
            cellOriginal = tableView.dequeueReusableCellWithIdentifier("HDBarcodeInputCell") as! HDBarcodeInputCell
            let cell = cellOriginal as! HDBarcodeInputCell
            cell.InputDelegate = self
            cell.titleView.text = "门店代码"
        case 2:
            cellOriginal = tableView.dequeueReusableCellWithIdentifier("HDProductInfocell") as! HDProductInfocell
            let cell = cellOriginal as! HDProductInfocell
            cell.titleView.text = "门店名称"
        case 1000...1999:
            cellOriginal = tableView.dequeueReusableCellWithIdentifier("HDJiHuoNumberTableViewCell") as! HDJiHuoNumberTableViewCell
            let cell = cellOriginal as! HDJiHuoNumberTableViewCell
            cell.Jihuodelegate = self
            var string = String()
            if dataArray1 == nil {
                cell.dict = ["middle" : "无数据"]
//                cell.label3.enabled = false
                cell.label3.hidden = true
            }else{
                for item in dataArray1! {
                    self.str = item["left"]! + "$$" + item["right"]! + "^^"
                    print("更新的self.str======\(self.str)")
                    string += (self.str)!
                }
                string.removeAtIndex(string.endIndex.predecessor())
                string.removeAtIndex(string.endIndex.predecessor())
                self.poChestInfo = string
                print("更新的array======\(self.poChestInfo)")
            }

            
            if let dataArr = dataArray1{
                cell.dict = dataArr[indexPath.row]
                let rightStr = cell.dict!["right"]
                let leftStr = cell.dict!["left"]
                print("rightStr = \(rightStr)")
                print("leftStr = \(leftStr)")
                if leftStr==""&&rightStr=="" {
                    cell.dict = ["middle" : "无数据"]
//                    cell.label3.enabled = false
                    cell.label3.hidden = true
                    self.piAttachMentInfo = leftStr!+rightStr!
                    print("str = \(self.poChestInfo)")
                }else{
//                    cell.label3.enabled = true
                    cell.label3.hidden = false
                    self.poChestInfo = leftStr!+"$$"+rightStr!
                    print("str = \(self.poChestInfo)")
                }
            }else{
                cell.dict = ["middle" : "无数据"]
//                cell.label3.enabled = false
                cell.label3.hidden = true
            }
        case 2000...2999:
            cellOriginal = tableView.dequeueReusableCellWithIdentifier("HDJiHuoNumberTableViewCell") as! HDJiHuoNumberTableViewCell
            let cell = cellOriginal as! HDJiHuoNumberTableViewCell
            cell.Jihuodelegate = self
            var string = String()
            if dataArray2 == nil {
                cell.dict = ["middle" : "无数据"]
//                cell.label3.enabled = false
                cell.label3.hidden = true
            }else{
                for item in dataArray2! {
                     self.str = item["left"]! + "$$" + item["right"]! + "^^"
                     print("更新的self.str======\(self.str)")
                    string += (self.str)!
                }
                string.removeAtIndex(string.endIndex.predecessor())
                string.removeAtIndex(string.endIndex.predecessor())
                self.piAttachMentInfo = string
                print("更新的array======\(self.piAttachMentInfo)")
            }
            if let dataArr = dataArray2{
                if dataArray1! == [["left": "", "right": ""]] {
                    cell.dict = dataArr[indexPath.row]
                    let rightStr = cell.dict!["right"]
                    let leftStr = cell.dict!["left"]
                    if leftStr==""&&rightStr=="" {
                        cell.dict = ["middle" : "无数据"]
                        cell.label3.enabled = false
                        cell.label3.hidden = false
                    }else{
                        cell.label3.enabled = false
                        cell.label3.hidden = false
                    }
                }else{
                    cell.dict = dataArr[indexPath.row]
                    let rightStr = cell.dict!["right"]
                    let leftStr = cell.dict!["left"]
                    if leftStr==""&&rightStr=="" {
                        cell.dict = ["middle" : "无数据"]
                        //                    cell.label3.enabled = false
                        cell.label3.hidden = true
                    }else{
                        //                    cell.label3.enabled = true
                        cell.label3.hidden = false
                    }
                }
              
            }else{
                cell.dict = ["middle" : "无数据"]
//                cell.label3.enabled = false
                cell.label3.hidden = true
            }
        default:
            cellOriginal = tableView.dequeueReusableCellWithIdentifier("HDProductInfocell") as! HDProductInfocell
        }
        if !self.reuseFlag {
            cellOriginal?.clearContent()
        }
        return cellOriginal!
    }
    
    //MARK: - tableViewDelegate
    override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        //           let sectionHeaders:[String] = [,]
        switch section {
        case 1:
            let view = FounctionSectionHeaderView(headerString: "复核容器,数量")
            return view
        case 2:
            let view = FounctionSectionHeaderView(headerString: "附件,数量")
            return view
        default:
            return nil
        }
    }
    override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return 10
        case 1,2:
            return 40
        default:
            return 0
        }
    }
    override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    
}
